namespace RBAC.Write.Api.Application.Handler.QualityHandler
{
    using MediatR;
    using Microsoft.Extensions.Logging;
    using RBAC.Domain.QualityManage;
    using RBAC.ErrorCode;
    using RBAC.Interstructrue.Base;
    using RBAC.Write.Api.Application.Command.QualityCommand;

    /// <summary>
    /// 更新质量工单 处理器。
    /// </summary>
    /// <remarks>
    /// 主要逻辑：
    /// 1. 校验 <c>Id</c> > 0，并加载未删除的实体。
    /// 2. 仅对提供的非空（或有值）字段进行增量更新，空值不覆盖原值。
    /// 3. 写入数据库，返回受影响行数；并统一处理取消与异常。
    /// </remarks>
    /// </summary>
    public class QualityOrderUpdateHandler : IRequestHandler<QualityOrderUpdateCommand, APIResult<int>>
    {
        private readonly IBaseRepository<QualityOrder> _orderRepo;
        private readonly ILogger<QualityOrderUpdateHandler> _logger;

        public QualityOrderUpdateHandler(IBaseRepository<QualityOrder> orderRepo, ILogger<QualityOrderUpdateHandler> logger)
        {
            _orderRepo = orderRepo;
            _logger = logger;
        }

        /// <summary>
        /// 处理“更新质量工单”请求。
        /// </summary>
        /// <param name="request">更新命令实体（增量更新）。</param>
        /// <param name="cancellationToken">取消令牌。</param>
        /// <returns>返回受影响行数的 <see cref="APIResult{T}"/>。</returns>
        public Task<APIResult<int>> Handle(QualityOrderUpdateCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<int>();
            try
            {
                // 检查是否被取消
                cancellationToken.ThrowIfCancellationRequested();
                // 参数校验：Id 必须有效
                if (request.Id <= 0)
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "Id无效", Data = 0 });

                // 查询未删除的原始实体
                var entity = _orderRepo.GetFirstOrDefault("Id = @Id AND IsDeleted = 0", new { Id = request.Id });
                if (entity == null)
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "质量工单不存在", Data = 0 });

                // 增量更新：仅对提供的字段进行更新，避免空值覆盖
                if (!string.IsNullOrWhiteSpace(request.Title)) entity.Title = request.Title!.Trim();
                if (!string.IsNullOrWhiteSpace(request.SourceWorkOrderNo)) entity.SourceWorkOrderNo = request.SourceWorkOrderNo;
                if (request.ProductId is > 0) entity.ProductId = request.ProductId;
                if (!string.IsNullOrWhiteSpace(request.ProductName)) entity.ProductName = request.ProductName;
                if (request.OwnerUserId is > 0) entity.OwnerUserId = request.OwnerUserId;
                if (!string.IsNullOrWhiteSpace(request.OwnerUserName)) entity.OwnerUserName = request.OwnerUserName;
                if (request.Status.HasValue) entity.Status = request.Status.Value;
                if (!string.IsNullOrWhiteSpace(request.Remark)) entity.Remark = request.Remark;

                // 仓储：提交更新并返回受影响行数
                var rows = _orderRepo.Update(entity);
                // 返回语义：rows > 0 视为成功
                result.Code = rows > 0 ? APIEnums.Success : APIEnums.Fail;
                result.Msg = rows > 0 ? "更新质量工单成功" : "更新质量工单失败";
                result.Data = rows;
            }
            catch (OperationCanceledException)
            {
                // 捕获取消异常
                _logger?.LogWarning("更新质量工单被取消");
                result.Code = APIEnums.Fail;
                result.Msg = "请求已取消";
                result.Data = 0;
            }
            catch (Exception ex)
            {
                // 统一异常处理与日志
                _logger?.LogError(ex, "更新质量工单失败: {Message}", ex.Message);
                result.Code = APIEnums.Fail;
                result.Msg = "更新质量工单失败";
                result.Data = 0;
            }

            return Task.FromResult(result);
        }
    }
}
